package com.le.tester.imooc.ccmouse.socket;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

/**
 * 描述：nio server
 */
public class NioServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        //不让他阻塞，一直可以处理请求
        socketChannel.configureBlocking(false);
        socketChannel.bind(new InetSocketAddress(8888));
        System.out.println("listening on " + socketChannel.getLocalAddress());

        //serverChannel注册到select中去
        Selector selector = Selector.open();
        //注册，通行
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        RequestHandler requestHandler = new RequestHandler();
        while (true) {
            int selected = selector.select();
            if (selected == 0) {
                continue;
            }
            //这个是根据key,获取val
            //Set<SelectionKey> selectionKeys = selector.keys();
            //需要的时候key值
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();

            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                if (key.isAcceptable()) {
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel clientChannel = channel.accept();

                    System.out.println("accepting incoming connection from " + clientChannel.getRemoteAddress());
                    clientChannel.configureBlocking(false);
                    clientChannel.register(selector, SelectionKey.OP_READ);
                }

                if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    channel.read(buffer);
                    String request = new String(buffer.array()).trim();
                    buffer.clear();
                    String response = requestHandler.handler(request);
                    channel.write(ByteBuffer.wrap(response.getBytes(StandardCharsets.UTF_8)));
                }
                keyIterator.remove();
            }
        }
    }
}
